package com.xiyuan.smartutils.template.engine.statement;

import com.xiyuan.smartutils.Validates;
import com.xiyuan.smartutils.template.engine.StatementParser;
import com.xiyuan.smartutils.template.engine.TagType;
import com.xiyuan.smartutils.template.engine.VariableMap;
import com.xiyuan.smartutils.template.engine.exception.StatementException;

import java.io.PrintWriter;
import java.util.Iterator;

public class _IF_ELSE extends Statement
{
    private static final long serialVersionUID = 1L;
    
    public _IF_ELSE(StatementParser statementParser)
    {
        super(statementParser);
    }
    
    @Override
    public void addStatement(Statement stmt)
    {
        if (stmt == null)
            return;
        
        if (stmt.getType() == TagType.ELSEIF || stmt.getType() == TagType.ELSE)
            this.getParent().addStatement(stmt);
        else
            super.addStatement(stmt);
    }
    
    protected void build(VariableMap variableMap, PrintWriter out)
    {
        Statement stmt = null;
        if(!hasChild())
            return;
        
        try
        {
            variableMap.newVariableSpace();// 创建局部变量空间
            
            Iterator<Statement> iterator = childs.iterator();
            while (iterator.hasNext())
            {// 循环内容
                stmt = iterator.next();
                stmt.execute(variableMap, out);
            }
        }
        finally
        {
            // 销毁局部变量空间
            variableMap.releaseVariableSpace();
        }
    }
    
    @Override
    public TagType getType()
    {
        return TagType.ELSE;
    }
    
    @Override
    public boolean parseTag(StatementParser parser) throws StatementException
    {
        StringBuilder value = new StringBuilder();
        while (parser.hasNext())
        {
            char ch = parser.next();
            if (value.length() == 0 && Validates.isWhitespace(ch))
                continue;
            
            value.append(ch);
            if (ch == _GATHER_)
            {
                this.setCompleteTag();
                break;
            }
            
        }
        
        if (value.length() != 1)
        {
            this.setStatement(this.getStatement() + value.toString());
            return false;// value 必须是一个字符并且 == ‘>’
        }
        
        this.setStatement(this.getStatement() + this.getType().getTagComplete());
        return true;
    }
    
}
